<template>
   <div class="app-container">
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets" style="margin-top: 5px"></i>
      <span style="margin-top: 5px">数据列表</span>
     
      <el-button
        class="btn-add"
        @click="showAddDialog()"
        size="mini">
        添加
      </el-button>
    </el-card>
    <el-dialog>
    </el-dialog>
    <div class="table-container">
      <el-table ref="productCateTable"
                style="width: 100%"
                :data="currentLevels"
                 border>
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{scope.$index+1}}</template>
        </el-table-column>
        <el-table-column label="阶段名称" align="center">
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>
        <el-table-column label="级别" align="center">
          <template slot-scope="scope">{{scope.row.level+1}}</template>
        </el-table-column>
        <el-table-column label="设置" align="center">
          <template slot-scope="scope"><el-button v-if="levelOptionFilter(scope.row.id,allLevelList).length>0" 
        @click="showChild(scope.row.id)" 
        size="mini">
        查看下级
      </el-button>
     <el-button v-if="scope.row.level > 0"
        @click="showParent()"  
        size="mini">
        回到上级
      </el-button>
  		</template>
        </el-table-column>
       
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="showUpdateDialog(scope.row)">编辑
            </el-button>
            <el-button v-if="levelOptionFilter(scope.row.id,allLevelList).length===0" 
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)" >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog title="添加阶段" :visible.sync="addFormVisible" :close-on-click-modal='false'>
	  <el-form :model="addForm" ref="addFormRef" :rules="addFormRule">
	    <el-form-item label="添加阶段名称"  prop="name">
	      <el-input v-model="addForm.name" autocomplete="off"></el-input>
	    </el-form-item>
	    
	     <el-form-item label="父阶段"  prop="parentIds">
	    	 <el-cascader  
                    :options="selectLevelOptions"
                   	v-model="addForm.parentIds"
                   	:props="{checkStrictly: true }"
                   
                    ></el-cascader>
	    </el-form-item>
	    
	  </el-form>
	  <div slot="footer" class="dialog-footer">
	    <el-button @click="addFormVisible = false">取 消</el-button>
	    <el-button type="primary" @click="handleAdd()">确 定</el-button>
	  </div>
  </el-dialog>
    <el-dialog title="修改阶段" :visible.sync="updateFormVisible" @close="handleUpdateCancel()" :close-on-click-modal='false'>
	  <el-form :model="updateForm" ref="updateFormRef" :rules="updateFormRule" >
	    <el-form-item label="修改阶段名称"  prop="name">
	      <el-input v-model="updateForm.name" autocomplete="off"></el-input>
	    </el-form-item>
	     <el-form-item label="父阶段"  prop="parentIds" >
		    <el-cascader  
	                    :options="selectLevelOptions"
	                    ref="updateCascaderRef"
	                   	v-model="updateForm.parentIds"
	                   	:props="{ checkStrictly: true }"
	                    
	                    size="middle"
	                    show-all-levels
	                    ></el-cascader>
         </el-form-item>
	    
	  </el-form>
	  <div slot="footer" class="dialog-footer">
	    <el-button @click="handleUpdateCancel()">取 消</el-button>
	    <el-button type="primary" @click="handleUpdate()">确 定</el-button>
	  </div>
  </el-dialog>
  </div>
</template>
<script type="text/javascript">
	import {mapGetters} from 'vuex'
	import store from '@/store'
	import {update as updateLevel} from '@/api/level'
	import {deletes as deleteLevel} from '@/api/level'
	import {add as addLevel} from '@/api/level'

	export default {
	    name: "levelList",
	    data() {
	      return {
	      	tempDisabledNode:null,  //updateForm里面不能把父节点改成自己，或者自己的子节点，所以临时把自己disabled
	      	currentParentIds:[0],  //父路径上所有的点组成的数组
	      
	      	currentLevels: null, // parentId=currentParentIds数组中最后一个元素的所有
	        list: null,
	        //添加阶段对话框相应的数据
	        addFormVisible:false,
	        addForm:{
	        	name:null,
	        	//parentIds:null,   //选择的节点，它会保存路径上所有的节点【2，3】
	        	parentIds:[0]
	        	
	        },
	        addFormRule :{
	          name: [{required: true, message: '请输入阶段名称', trigger: 'blur'}],
	          parentIds: [{required: true, message: '请选择父阶段', trigger: 'blur'}],
	        },

	        
	        //修改阶段对话框相应的数据
	        updateFormVisible:false,
	        updateForm:{
	        	id:null,
	        	name:null,
	        	parentIds:null,
	        	
	        },
	        updateFormRule :{
	          name: [{required: true, message: '请输入阶段名称', trigger: 'blur'}],
	          parentIds: [{required: true, message: '请选择父阶段', trigger: 'blur'}],
	        },
	        
	       

	      }
	    },
	    computed:{
	    	...mapGetters([
	          'allLevelList',
	          'leaveLevelOptions',
	          'levelOptions',
	          
	        ]),

	    	selectLevelOptions(){
	    		
	    		var newLevelTree

	    		newLevelTree= JSON.parse(JSON.stringify(this.levelOptions));
	    		if (newLevelTree!=null){
	    			newLevelTree.push({label: "无", value: 0,level:0});
	    		}else{
	    			newLevelTree=[{label: "无", value: 0,level:0}]
	    		}
	    		
	    		
	    		return newLevelTree

	    	}
	        
	       
        },
        created(){
        	this.currentLevels=this.levelOptionFilter(this.currentParentIds[this.currentParentIds.length-1],this.allLevelList)

        },
        watch:{
        	currentParentIds:function (newValue){
        		this.currentLevels=this.levelOptionFilter(newValue[newValue.length-1],this.allLevelList)
        	}
        },
       
	    methods:{
	    	/*
			获取所有x.parentId===parentId的项目，作为数组返回
			*/
			levelOptionFilter(parentId,options) {
				if (options===null){
					return []
				}
		        let res= options.filter(function(x) {
		          return x.parentId ===parentId;
		          }
		        )

		        return res
		    },
		    getNodefromId(id,options){
		    	 let res= options.find(function(x) {
		          return x.id ===id;
		          }
		        )
		    	return res
   

		    },
		    getNodefromValueInTree(value,options){
		    	 var childNode=null
		    	 for(var i in options){
		    	
		    	 	if (options[i].value===value) {
				    		return options[i]
				    } else{
				    	if (options[i].hasOwnProperty('children')){
				    		//console.log(options[i])
				    		childNode= this.getNodefromValueInTree(value,options[i].children)
				    		if (childNode) return childNode
				    	
				    	}
				    	
				    }
				  

				  }
				  return null
   

		    },
		    //通过parentId的level，得到自己的level
		    getSelectedLevel(parentId){
		    	var selectedLevel=0
	    		if (parentId===0){
	    			selectedLevel=0
	    		}else{
	    			var selectedParentNode=this.getNodefromId(parentId,this.allLevelList)
	    			selectedLevel=selectedParentNode.level+1
	    		}
	    		return selectedLevel
		    },
		    showChild(parentId){
		    	
		    	this.currentParentIds.push(parentId)
		    	
		    },
		    showParent(){
		    	
		    	this.currentParentIds.pop()
		    	
		    },
	    	showAddDialog(){
	    		this.addForm.name=''
	    		this.addForm.parentIds=null
	    		this.addFormVisible=true
	    	},
	    	handleAdd() {
	    		
	    		
	    		this.$refs.addFormRef.validate(valid => {
	    			if (valid) {
	    				var parentId=this.addForm.parentIds[this.addForm.parentIds.length-1]
	    				
	    				var selectedLevel=this.getSelectedLevel(parentId)
	    				var name=this.addForm.name
	    				
			    		addLevel({"name":name,"parentId":parentId,"level":selectedLevel}).then(response=>{
			    			
			    			
			    			this.$store.dispatch('GetLevelListAll')
				    		this.addFormVisible=false
				    		this.$message({
				                type: 'success',
				                message: '添加成功',
				                duration:1000
				             });


			    		}).catch(error=>{
			    			 this.addFormVisible=false
			    			 this.$message({
				                type: 'error',
				                message: '添加失败',
				                duration:1000
				             });
			    		})
			    	}
        		})
		    },
		   
		    showUpdateDialog(row){
	    		this.updateForm.name=row.name
	    		this.updateForm.id=row.id
	    		this.updateForm.parentIds=[]
	    		if (row.parentId===0)
	    			this.updateForm.parentIds=[row.parentId]
	    		else{
	    			for (var i=1; i<this.currentParentIds.length;i++){
	    				//去掉currentParentIds的第一个元素0
	    				this.updateForm.parentIds.push(this.currentParentIds[i])
	    			}
	    			
	    		}
	    		
	    		this.tempDisabledNode=this.getNodefromValueInTree(this.updateForm.id,this.selectLevelOptions)
	    		this.tempDisabledNode.disabled=true
	    		
	    		this.updateFormVisible=true
	    	},
	    	handleUpdateCancel(){
	    		this.updateFormVisible=false
				    		
	    		this.tempDisabledNode.disabled=false
	    		//this.tempDisabledNode=null
	    	},
	    	handleUpdate(id,name,parentId) {
	    		var that=this
	    		
	    		
        		this.$refs.updateFormRef.validate(valid => {
	    			if (valid) {
	    				var id=that.updateForm.id
	    				var name=that.updateForm.name
	    				var parentId=that.updateForm.parentIds[that.updateForm.parentIds.length-1]

	    				var selectedLevel=0
			    		if (parentId===0){
			    			selectedLevel=0
			    		}else{
			    			var selectedParentNode=that.getNodefromId(parentId,that.allLevelList)
			    			selectedLevel=selectedParentNode.level+1
			    		}

		        		updateLevel({"id":id,"name":name,"parentId":parentId,"level":selectedLevel}).then(response=>{
		        			
				    		this.$store.dispatch('GetLevelListAll')

				    		this.updateFormVisible=false
				    		
				    		
	    					that.tempDisabledNode.disabled=false
	    					//hat.tempDisabledNode=null

					    	this.$message({
						                type: 'success',
						                message: '更新成功',
						                duration:1000
						             });
			    			

			    		}).catch(error=>{
			    			this.updateFormVisible=false
			    			
	    					that.tempDisabledNode.disabled=false
	    					//that.tempDisabledNode=null
					    			 this.$message({
						                type: 'error',
						                message: '更新失败',
						                duration:1000
						             });
			    			})
			    	}
			    }) 
		    },

		    handleDelete( row) {
		        this.$confirm('是否要删除该阶段？如果删除，将彻底删除子阶段以及所有相关的试题，知识点和题目来源！', '提示', {
		          confirmButtonText: '确定',
		          cancelButtonText: '取消',
		          type: 'warning'
		        }).then(() => {
		          	 this.$confirm('再次确认删除该阶段？', '提示', {
				          confirmButtonText: '确定',
				          cancelButtonText: '取消',
				          type: 'warning'
				        }).then(() => {
				        	
				        	deleteLevel({"id":row.id}).then(response=>{
					    		this.$store.dispatch('GetLevelListAll')
					    		this.$message({
					                type: 'success',
					                message: '删除成功',
					                duration:1000
					            });
					    	}).catch(() => {
		          				this.$message({
					                type: 'error',
					                message: '删除失败',
					                duration:1000
					            });
		          
		       				});


				        }).catch(() => {
		          				
		          
		       			 });
		          
		        }).catch(() => {
		          	
		          
		        });
		      }
	    }
	    
	}
	
	
</script>
<style type="text/css" scoped="">
	input::-webkit-input-placeholder {
      color:#717171 !important;
    }
    input::-moz-placeholder {
      /* Mozilla Firefox 19+ */
      color:#717171 !important;
    }
    input:-moz-placeholder {
      /* Mozilla Firefox 4 to 18 */
      color:#717171 !important;
    }
    input:-ms-input-placeholder {
      /* Internet Explorer 10-11 */
      color:#717171 !important;
    }

</style>